/**
 * Created by xixin on 6/26/2015.
 */

//Address related js
function setAddressValue(provinceId, provinceVal, cityId, cityValue, countyId, countyValue){
  dwr.util.setValue(provinceId, provinceVal);
  var prov_id = dwr.util.getValue(provinceId);
  ProvinceManager.getMyCity(prov_id, function(data) {
    dwr.util.addOptions(cityId, data, "name");
    dwr.util.setValue(cityId, cityValue);
    if (cityValue) {
      CityManager.getMyCounty(cityValue, function(data) {
        dwr.util.addOptions(countyId, data, "name");
        dwr.util.setValue(countyId, countyValue);
      })
    }
  })
}

function resetCityAndCounty(cityOption, countyOption, provinceId, cityId, countyId){
  cityOption.remove();
  countyOption.remove();
  var prov_id = dwr.util.getValue(provinceId);
  ProvinceManager.getMyCity(prov_id, function(data) {
    dwr.util.addOptions(cityId, data, "name");
    var city_id = dwr.util.getValue(cityId);
    CityManager.getMyCounty(city_id, function(data) {
      dwr.util.addOptions(countyId, data, "name");
    })
  })
}

function resetCounty(countyOption, cityId, countyId){
  countyOption.remove();
  var city_id = dwr.util.getValue(cityId);
  CityManager.getMyCounty(city_id, function(data) {
    dwr.util.addOptions(countyId, data, "name");
  })
}

if($("#hkprovinceValue").val()){
  setAddressValue('hkprovince', $("#hkprovinceValue").val(), 'hkcity', $("#hkcityValue").val(), 'hkcounty', $("#hkcountyValue").val());
}
$('#hkprovince').change(function() {
  resetCityAndCounty($('#hkcity option'), $('#hkcounty option'), 'hkprovince', 'hkcity', 'hkcounty');
});
$('#hkcity').change(function() {
  resetCounty( $('#hkcounty option'), 'hkcity', 'hkcounty');
});

if ($('#provinceValue').val()) {
  setAddressValue('province', $('#provinceValue').val(), 'city', $('#cityValue').val(), 'county', $('#countyValue').val());
}
if ($('#comProvinceValue').val()) {
  setAddressValue('comProvince', $('#comProvinceValue').val(), 'comCity', $('#comCityValue').val(), 'comCounty', $('#comCountyValue').val());
}
if ($('#coProvinceValue').val()) {
  setAddressValue('coProvince', $('#coProvinceValue').val(), 'coCity', $('#coCityValue').val(), 'coCounty', $('#coCountyValue').val());
}
if ($('#comCoProvinceValue').val()) {
  setAddressValue('comCoProvince', $('#comCoProvinceValue').val(), 'comCoCity', $('#comCoCityValue').val(), 'comCoCounty', $('#comCoCountyValue').val());
}
if ($('#dbProvinceValue').val()) {
  setAddressValue('dbProvince', $('#dbProvinceValue').val(), 'dbCity', $('#dbCityValue').val(), 'dbCounty', $('#dbCountyValue').val());

}
if ($('#comDbProvinceValue').val()) {
  setAddressValue('comDbProvince', $('#comDbProvinceValue').val(), 'comDbCity', $('#comDbCityValue').val(), 'comDbCounty', $('#comDbCountyValue').val());
}

$('#province').change(function() {
  resetCityAndCounty( $('#city option'), $('#county option'), 'province', 'city', 'county');
});

$('#city').change(function() {
  resetCounty($('#county option'), 'city', 'county');
});
$('#comProvince').change(function() {
  resetCityAndCounty($("#comCity option"), $("#comCounty option"), 'comProvince', 'comCity', 'comCounty');
});

$('#comCity').change(function() {
  resetCounty($('#comCounty option'), 'comCity', 'comCounty');

});
$('#coProvince').change(function() {
  resetCityAndCounty( $('#coCity option'), $('#coCounty option'), 'coProvince', 'coCity', 'coCounty');
});

$('#coCity').change(function() {
  resetCounty($('#coCounty option'), 'coCity', 'coCounty');
});
$('#comCoProvince').change(function() {
  resetCityAndCounty( $('#comCoCity option'), $('#comCoCounty option'), 'comCoProvince', 'comCoCity', 'comCoCounty');
});
$('#comCoCity').change(function() {
  resetCounty($('#comCoCounty option'), 'comCoCity', 'comCoCounty');
});
$('#dbProvince').change(function() {
  resetCityAndCounty( $('#dbCity option'), $('#dbCounty option'), 'dbProvince', 'dbCity', 'dbCounty');
});

$('#dbCity').change(function() {
  resetCounty($('#dbCounty option'), 'dbCity', 'dbCounty');
});

$('#comDbProvince').change(function() {
  resetCityAndCounty( $('#comDbCity option'), $('#comDbCounty option'), 'comDbProvince', 'comDbCity', 'comDbCounty');
});

$('#comDbCity').change(function() {
  resetCounty($('#comDbCounty option'), 'comDbCity', 'comDbCounty');
});

$("#dueDate").datepicker({
  minDate: new Date()
});
$("#coDueDate").datepicker({
  minDate: new Date()
});
$("#dbDueDate").datepicker({
  minDate: new Date()
});
// calculate the loan price
function clearVehicle() {
  $("#vehicleBrand").val('');
  $("#vehicleBrandValue").val('');
  $("#vehicleSeries").val('');
  $("#vehicleSeriesValue").val('');
  $("#vehicleModel").val('');
  $("#vehicleModelValue").val('');
  $("#manufacturerPrice").val(0.0);
  $('#vehicleBrand option').remove();
  $('#vehicleModel option').remove();
  $('#vehicleSeries option').remove();
  $("#loanProduct").val('');
  $('#loanProductIdValue').val('');
  $("#loanYearsValue").val('');
  $('#loanProduct option').remove();
  $("#loanYears option").remove();

}
document.models = {};
document.second = $("#loanRequestSecond").val() == 'true';
$("#second").change(function() {
  clearVehicle();
  clearLoanProduct();
  clearAmount();
  if ($("#second").prop('checked')) {
    document.second = true;
  } else {
    document.second = false;
  }
  reloadVehicleBrand();
  reloadProduct();
});

reloadVehicleBrand();
reloadProduct();

function reloadProduct() {
  $("#loanYears option").remove();
  var bondId = parseFloat($("#bondId").val());
  LoanProductManager.getLoanProductsByBond(bondId, document.second, function(data) {
    dwr.util.addOptions('loanProduct', data, 'id', 'productName');
    if ($("#loanProductIdValue").val()) {
      dwr.util.setValue('loanProduct', $("#loanProductIdValue").val());
    }
    if ($("#loanProduct").val()) {


      LoanProductManager.getById($("#loanProduct").val(), function(data) {
        getLoanYears(data.loanYears)
        if ($("#loanYearsValue").val()) {
          dwr.util.setValue('loanYears', $("#loanYearsValue").val());
        }
        handleLoanProduct($("#loanProduct").val());
      })
    }
  })
}

function reloadVehicleBrand() {
  VehicleBrandManager.getAllBrands(document.second, function(data) {
    dwr.util.addOptions('vehicleBrand', data, 'brand');
    if ($("#vehicleBrandValue").val()) {
      dwr.util.setValue('vehicleBrand', $("#vehicleBrandValue").val());
    }
    var brand_id = dwr.util.getValue('vehicleBrand');
    VehicleBrandManager.getMySeries(brand_id, document.second, function(data) {
      if (data.length > 0) {
        dwr.util.addOptions('vehicleSeries', data, 'name');
        if ($('#vehicleSeriesValue').val()) {
          dwr.util.setValue('vehicleSeries', $('#vehicleSeriesValue').val());
        }
        var series_id = $("#vehicleSeries").val();
        VehicleSeriesManager.getMyModels(series_id, document.second, function(data) {
          dwr.util.addOptions('vehicleModel', data, 'name');
          if ($('#vehicleModelValue').val()) {
            dwr.util.setValue('vehicleModel', $('#vehicleModelValue').val());
          }
          document.models = {};
          data.forEach(function(dd) {
            if (!document.second) {
              document.models[dd.name] = dd.guidePrice;
            } else {
              document.models[dd.name] = dd.secondPrice;
            }
          });
          var model = dwr.util.getValue('vehicleModel');
          $('#manufacturerPrice').val(document.models[model]);
        })
      }
    })

  })
}


$('#vehicleBrand').change(function() {
  $('#vehicleModel option').remove();
  $('#vehicleSeries option').remove();
  clearAmount();
  $('#manufacturerPrice').val(0.0);
  var brand_id = dwr.util.getValue('vehicleBrand');
  VehicleBrandManager.getMySeries(brand_id, document.second, function(data) {
    if (data.length > 0) {
      dwr.util.addOptions('vehicleSeries', data, 'name');
      var series_id = dwr.util.getValue('vehicleSeries');
      VehicleSeriesManager.getMyModels(series_id, document.second, function(data) {
        dwr.util.addOptions('vehicleModel', data, 'name');
        document.models = {};
        data.forEach(function(dd) {
          if (!document.second) {
            document.models[dd.name] = dd.guidePrice;
          } else {
            document.models[dd.name] = dd.secondPrice;
          }
        })
        var model = dwr.util.getValue('vehicleModel');
        $('#manufacturerPrice').val(document.models[model]);
      })
    }

  })
});

$('#vehicleSeries').change(function() {
  $('#vehicleModel option').remove();
  $('#manufacturerPrice').val(0.0);
  clearAmount();
  var series_id = dwr.util.getValue('vehicleSeries');
  VehicleSeriesManager.getMyModels(series_id, document.second, function(data) {
    dwr.util.addOptions('vehicleModel', data, 'name');
    document.models = {};
    data.forEach(function(dd) {
      if (!document.second) {
        document.models[dd.name] = dd.guidePrice;
      } else {
        document.models[dd.name] = dd.secondPrice;
      }
    })
    var model = dwr.util.getValue('vehicleModel');
    $('#manufacturerPrice').val(document.models[model]);
  })
});

$('#vehicleModel').change(function() {
  var model = dwr.util.getValue('vehicleModel');
  $('#manufacturerPrice').val(document.models[model]);
  clearAmount();
});


document.product = {};

function clearLoanProduct() {
  document.product = {};
  $("#loanYearMax").html('');
  $("#downPaymentRateDesc").html('');
  $("#loanAmountDesc").html('');
  $("#feeRateDesc").html('');
  $('#loanRate').val(0.0);
  $("#monthPaymentAmount").val(0.0);
  $("#totalReturnAmount").val(0.0);
}

function clearAmount() {
  var status = $("#status").val();
  if (status == 'dealer_submit') {
    $("#feeRate").val(0.0);
  }
  $("#downPaymentRate").val(0.0);
  $("#downPaymentAmount").val(0.0);
  $("#monthPaymentAmount").val(0.0);
  $("#totalReturnAmount").val(0.0);
  $("#loanAmount").val(0.0);
}

function getLoanYears(years) {
  var selectedYear = $("#loanYearsValue").val();
  var yearList = [];
  if (years.length > 0) {
    $("#loanYears option").remove();
    for (var i = 0; i < years.length; i++) {
      yearList.push({
        'value': years[i],
        'label': years[i] + '年'
      })
    }
    dwr.util.addOptions("loanYears", yearList, "value", "label");
    dwr.util.setValue('loanYears', selectedYear);
  }

}

function handleLoanProduct(productId) {
  if(productId){
  LoanProductManager.getById(productId, function(data) {
    document.product = data;
    document.product.salePrice = parseFloat($("#price").val()) || 0.0;
    var product = document.product;
    $('#loanRate').val(data.coef);
    //$("#loanYearMax").html('最大贷款年限:'+);
    getLoanYears(product.loanYears);
    $("#downPaymentRateDesc").html("首付比例范围：" + product.dpLL + "到" + product.dpUL);
    $("#loanAmountDesc").html("贷款金额范围：" + product.faLL + '到' + product.faUL);
    $("#feeRateDesc").html("手续费率范围：" + product.crLL + '到' + product.crUL);
    doLoanPriceChange()
  })
  }
}

function doLoanPriceChange() {
  var salePrice = parseFloat($("#price").val());
  if (salePrice > $("#manufacturerPrice").val()) {
    $("#priceError").html("销售价格不可以大于厂商指导价");
  } else {
    $("#priceError").html("");
  }
  var downPaymentAmount = parseFloat($("#downPaymentAmount").val());
  var downPaymentRate = parseFloat($("#downPaymentRate").val());
  $("#downPaymentRateDesc").html("首付比例范围：" + document.product.dpLL + "到" + document.product.dpUL);
  if (downPaymentRate < document.product.dpLL || downPaymentRate > document.product.dpUL) {
    $("#downPaymentRateDescError").html("首付比例不在范围内");
  } else {
    $("#downPaymentRateDescError").html("");
  }
  var loanAmount = parseFloat($("#loanAmount").val());
  var loanYears = parseFloat($("#loanYears").val());
  if (salePrice >= 0 && downPaymentAmount >= 0) {
    $("#loanAmount").val(salePrice - downPaymentAmount);
  } else {
    $("#loanAmount").val(0.0);
  }

  if ((salePrice - downPaymentAmount) < document.product.faLL || (salePrice - downPaymentAmount) > document.product.faUL) {
    $("#loanAmountDesc").html("贷款金额范围：" + document.product.faLL + '到' + document.product.faUL);
  } else {
    $("#loanAmountDesc").html("");
  }
  var feeRate = parseFloat($("#feeRate").val()) / 100;
  if (feeRate * 100 < document.product.crLL || feeRate * 100 > document.product.crUL) {
    $("#feeRateDesc").html("手续费率范围：" + document.product.crLL + '到' + document.product.crUL);
    $("#feeRateError").html("手续费率不在范围内！");
  } else {
    $("#feeRateError").html("");
  }
  if (loanAmount && loanYears) {
    calculateMonth();
  }
}

// 10万车价贷款额70%共七万，这里七万指的就是贷款本金。放款金额指的是银行实际放款额=贷款本金*（1+客户费率-成本费率）。客户月供=实际放款额*（1+成本费率）／36
function calculateMonth() {
  var loanRate = parseFloat($("#loanRate").val()) / 100;
  var feeRate = parseFloat($("#feeRate").val()) / 100; // 客户费率
  $("#feeRateDesc").html("手续费率范围：" + document.product.crLL + '到' + document.product.crUL);
  if (feeRate * 100 < document.product.crLL || feeRate * 100 > document.product.crUL) {
    $("#feeRateError").html("手续费率不在范围内！");
  } else {
    $("#feeRateError").html("");
  }
  var loanAmount = parseFloat($("#loanAmount").val()); // 贷款本金
  var loanMonth = parseFloat($("#loanYears").val()) * 12;
  var monthPay = 0.0;
  var costRate = parseFloat(document.product.costRate/100); // 成本费率
  if (loanRate == 0.0 && feeRate > 0) {
    //monthPay = Math.round(loanAmount*(1+feeRate)/loanMonth*100)/100; //按照费率算：贷款金额*（1+费率）/期限=月供
    monthPay = Math.round(loanAmount * (1 + feeRate - costRate) * (1 + costRate) / loanMonth * 100) / 100; //月供计算公式： 车价*（1-首付比例) * (1+手续费率-成本费率）*(1+成本费率）/贷款年限
  } else if (loanRate > 0) {
    loanAmount = loanAmount * (1 + feeRate);
    var monthO = loanAmount * loanRate * Math.pow((1 + loanRate), loanMonth) / (Math.pow((1 + loanRate), loanMonth) - 1);
    monthPay = Math.round(monthO * 100) / 100;
  }

  $("#monthPaymentAmount").val(monthPay);
  $("#totalReturnAmount").val(Math.round(monthPay * loanMonth * 100) / 100);
  var totalLoanAmount = Math.round(loanAmount * (1 + feeRate - costRate) * 100) /100;
  if($("#totalLoanAmount")){
    $("#totalLoanAmount").html(totalLoanAmount);
  }
}

$('#manufacturerPrice').change(function() {
  clearAmount();
});

$('#loanProduct').change(function() {
  var product_id = parseInt($('#loanProduct').val());
  if (product_id) {
    handleLoanProduct(product_id)
  } else {
    clearLoanProduct();
  }
});

$("#price").on('input', function(e) {
  var product_id = parseInt($('#loanProduct').val());
  if (product_id) {
    doLoanPriceChange();
  }
});

$("#price").change( function(e) {
  var salePrice = parseFloat($("#price").val());
  var downPaymentRate = parseFloat($("#downPaymentRate").val());
  $("#downPaymentAmount").val(downPaymentRate / 100 * salePrice);
  var product_id = parseInt($('#loanProduct').val());
  if (product_id) {
    doLoanPriceChange();
  }
});

$("#downPaymentAmount").on('input', function(e) {
  var salePrice = parseFloat($("#price").val());
  var downPaymentAmount = parseFloat($("#downPaymentAmount").val());
  $("#downPaymentRate").val(Math.round(downPaymentAmount / salePrice * 100 * 100) / 100);
  var product_id = parseInt($('#loanProduct').val());
  if (product_id) {
    doLoanPriceChange();
  }
});

$("#downPaymentRate").on('input', function(e) {
  var salePrice = parseFloat($("#price").val());
  var downPaymentRate = parseFloat($("#downPaymentRate").val());
  $("#downPaymentAmount").val(downPaymentRate / 100 * salePrice);
  var product_id = parseInt($('#loanProduct').val());
  if (product_id) {
    doLoanPriceChange()
  }
});

$("#loanYears").change(function() {
  calculateMonth();
  if($("#creditType").val()=='2'){
    calculateIncome();
  }
});

$("#feeRate").on('input', function(e) {
  var product_id = parseInt($('#loanProduct').val());
  if (product_id) {
    doLoanPriceChange()
  }
});

if ($("#loanProduct").val() || $("#loanProductIdValue").val()) {
  handleLoanProduct(parseInt($('#loanProduct').val()));
}

function validateNumber(e){
  var r = /^\+?[1-9][0-9]*$/;
  if (r.test($("#companyYears").val()) && r.test($("#liveYears").val()))
  {
    $("#companyYears").parent().removeClass('has-error');
    $("#liveYears").parent().removeClass('has-error');
    //$("#save").attr('disabled',false);
    $("#submitRequest").attr('disabled',false);
  }
  else {
    if (!r.test($("#companyYears").val())) {
      $("#companyYears").parent().addClass('has-error');
      //$("#save").attr('disabled', true);
      $("#submitRequest").attr('disabled', true);
    }
    else{
      $("#companyYears").parent().removeClass('has-error');
    }
    if (!r.test($("#liveYears").val())) {
      $("#liveYears").parent().addClass('has-error');
      //$("#save").attr('disabled', true);
      $("#submitRequest").attr('disabled', true);
    }
    else{
      $("#liveYears").parent().removeClass('has-error');
    }
  }
}

// validation for mobile
function validateMobile() {
  var fitPhone = /^[1][358]\d{9}$/;
  var number = $("#mobileNo").val();
  if (number) {
    if (fitPhone.test(number)) {
      $("#mobileValidate").html('验证中')
      $.ajax("/mobileValidate?mobile=" + number, {
        success: function(data) {

          $("#mobileValidate").html(decodeURI(data));
        },
        timeout: 100000,
        error: function() {
          $("#mobileValidate").html('查询失败！');
        }
      })
    } else {
      $("#mobileValidate").parent().addClass('has-error')
      $("#mobileValidate").html('手机号不合法');
    }
  }
  var coNumber = $("#coMobileNo").val();
  if (coNumber) {
    if (fitPhone.test(coNumber)) {
      $("#coMobileValidate").html('验证中')
      $.ajax("/mobileValidate?mobile=" + coNumber, {
        success: function(data) {
          $("#coMobileValidate").html(decodeURI(data));
        },
        timeout: 100000,
        error: function() {
          $("#coMobileValidate").html('查询失败！');
        }
      })
    } else {
      $("#coMobileValidate").parent().addClass('has-error')
      $("#coMobileValidate").html('手机号不合法');
    }
  }
  var dbNumber = $("#dbMobileNo").val();
  if (dbNumber) {
    if (fitPhone.test(dbNumber)) {
      $("#dbMobileValidate").html('验证中')
      $.ajax("/mobileValidate?mobile=" + dbNumber, {
        success: function(data) {
          $("#dbMobileValidate").html(decodeURI(data));
        },
        timeout: 100000,
        error: function() {
          $("#dbMobileValidate").html('查询失败！');
        }
      })
    } else {
      $("#dbMobileValidate").parent().addClass('has-error')
      $("#dbMobileValidate").html('手机号不合法');
    }
  }
  var urgentContactTelNo1 = $("#urgentContactTelNo1").val();
  if (urgentContactTelNo1) {
    if (fitPhone.test(urgentContactTelNo1)) {
      $("#urgentContactTelNo1").html('验证中')
      $.ajax("/mobileValidate?mobile=" + urgentContactTelNo1, {
        success: function(data) {
          $("#urgentContactTelNo1Validate").html(decodeURI(data));
        },
        timeout: 100000,
        error: function() {
          $("#urgentContactTelNo1Validate").html('查询失败！');
        }
      })
    } else {
      $("#urgentContactTelNo1Validate").parent().addClass('has-error')
      $("#urgentContactTelNo1Validate").html('手机号不合法');
    }
  }
  var urgentContactTelNo2 = $("#urgentContactTelNo2").val();
  if (urgentContactTelNo2) {
    if (fitPhone.test(urgentContactTelNo2)) {
      $("#urgentContactTelNo2").html('验证中')
      $.ajax("/mobileValidate?mobile=" + urgentContactTelNo2, {
        success: function(data) {
          $("#urgentContactTelNo2Validate").html(decodeURI(data));
        },
        timeout: 100000,
        error: function() {
          $("#urgentContactTelNo2Validate").html('查询失败！');
        }
      })
    } else {
      $("#urgentContactTelNo2Validate").parent().addClass('has-error')
      $("#urgentContactTelNo2Validate").html('手机号不合法');
    }
  }
  var urgentContactTelNo3 = $("#urgentContactTelNo3").val();
  if (urgentContactTelNo3) {
    if (fitPhone.test(urgentContactTelNo3)) {
      $("#urgentContactTelNo3").html('验证中')
      $.ajax("/mobileValidate?mobile=" + urgentContactTelNo3, {
        success: function(data) {
          $("#urgentContactTelNo3Validate").html(decodeURI(data));
        },
        timeout: 100000,
        error: function() {
          $("#urgentContactTelNo3Validate").html('查询失败！');
        }
      })
    } else {
      $("#urgentContactTelNo3Validate").parent().addClass('has-error')
      $("#urgentContactTelNo3Validate").html('手机号不合法');
    }
  }
}

// check date
function check(date, selector) {
  var a = /^(\d{2})\/(\d{2})\/(\d{4})$/
  if (!a.test(date) && date) {
    alert("日期格式不正确!");
    selector.val('');
    return false
  }
  return true;
}

//check ID and birthday
function validateId() {
  if ($("#idType").val() == 'Identity' && $("#idNo").val()) {
    var idNo = $("#idNo").val();
    var birthday = $("#birthday").val();
    if (idNo && check(birthday, $("#birthday"))) {
      $("#idValidate").html('验证中');
      $.ajax("/idcardValidate?idcard=" + idNo + (birthday ? ("&birthday=" + birthday) : ''), {
        success: function(data) {
          if (data != 'success') {
            $("#idValidate").parent().addClass('has-error')
            $("#idValidate").html(data);
          } else {
            $("#idValidate").parent().removeClass('has-error')
            $("#idValidate").html('');
          }

        }
      })
    }
  } else {
    $("#idValidate").parent().removeClass('has-error')
    $("#idValidate").html('');
  }

  if ($("#coIdType").val() == 'Identity' && $("#coIdNo").val()) {
    var coIdNo = $("#coIdNo").val();
    birthday = $("#coBirthday").val();
    if (coIdNo && check(birthday, $("coBirthday"))) {
      $("#coIdValidate").html('验证中');
      $.ajax("/idcardValidate?idcard=" + coIdNo + (birthday ? ("&birthday=" + birthday) : ''), {
        success: function(data) {
          if (data != 'success') {
            $("#coIdValidate").parent().addClass('has-error')
            $("#coIdValidate").html(data);
          } else {
            $("#coIdValidate").parent().removeClass('has-error')
            $("#coIdValidate").html('');
          }

        }
      })
    }
  } else {
    $("#coIdValidate").parent().removeClass('has-error')
    $("#coIdValidate").html('');
  }
  if ($("#dbIdType").val() == 'Identity' && $("#dbIdNo").val()) {
    var dbIdNo = $("#dbIdNo").val();
    birthday = $("#dbBirthday").val();
    if (dbIdNo && check(birthday, $("#dbBirthday"))) {
      $("#dbIdValidate").html('验证中');
      $.ajax("/idcardValidate?idcard=" + dbIdNo + (birthday ? ("&birthday=" + birthday) : ''), {
        success: function(data) {
          if (data != 'success') {
            $("#dbIdValidate").parent().addClass('has-error')
            $("#dbIdValidate").html(data);
          } else {
            $("#dbIdValidate").parent().removeClass('has-error')
            $("#dbIdValidate").html('');

          }

        }
      })
    }
  } else {
    $("#dbIdValidate").parent().removeClass('has-error')
    $("#dbIdValidate").html('');
  }
}

$("#companyYears").change(function(){
  validateNumber($("#companyYears"));
});

$("#liveYears").change(function(){
  validateNumber($("#liveYears"));
});

function validateNumberForApply(e){
  var r = /^([1-9][\d]{0,7}|0)(\.[\d]{1,2})?$/;
  if (r.test($("#premiumAmount").val()) && r.test($("#insuranceAmount").val()))
  {
    $("#premiumAmount").parent().removeClass('has-error');
    $("#insuranceAmount").parent().removeClass('has-error');
    $("#applyLoan").attr('disabled',false);
  }
  else {
    if (!r.test($("#premiumAmount").val())) {
      $("#premiumAmount").parent().addClass('has-error');
      $("#applyLoan").attr('disabled', true);
    }
    else {
      $("#premiumAmount").parent().removeClass('has-error');
    }
    if (!r.test($("#insuranceAmount").val())){
      $("#insuranceAmount").parent().addClass('has-error');
      $("#applyLoan").attr('disabled',true);
    }
    else{
      $("#insuranceAmount").parent().removeClass('has-error');
    }
  }

}

$("#premiumAmount").change(function(){
  validateNumberForApply($("#premiumAmount"));
});

$("#insuranceAmount").change(function(){
  validateNumberForApply($("#insuranceAmount"));
});

$("#mobileNo").change(function() {
  validateMobile()
});
$("#coMobileNo").change(function() {
  validateMobile()
});
$("#dbMobileNo").change(function() {
  validateMobile()
});
$("#urgentContactTelNo1").change(function() {
  validateMobile()
});
$("#urgentContactTelNo2").change(function() {
  validateMobile()
});
$("#urgentContactTelNo3").change(function() {
  validateMobile()
});

validateMobile();

$("#idNo").change(function() {
  validateId();
});
$("#coIdNo").change(function() {
  validateId();
});
$("#dbIdNo").change(function() {
  validateId();
});
$("#idType").change(function() {
  validateId();
});
$("#coIdType").change(function() {
  validateId();
});
$("#dbIdType").change(function() {
  validateId();
});
validateId();

// do effect when click coLoanded and dbLoanded
$("input#loanRequestCoLoaned[type=checkbox]").on("click", function() {
  $("#coLoanBtn").click();
});
$("input#loanRequestGuaranted[type=checkbox]").on("click", function() {

  $("#guarantedBtn").click();

});
// END do effect when click coLoaned and dbLoaned

// calculate ages for requestor/coPerson/dbPerson
if ($("#birthday").val()) {
  var today = new Date();
  var birthday = new Date($("#birthday").val());
  $("#requestorAge").val((today.getYear() - birthday.getYear()) + '岁');
  $("#requestorAge").html((today.getYear() - birthday.getYear()) + '岁');
}

$("#birthday").change(function() {
  var today = new Date();
  var birthday = new Date($("#birthday").val());
  $("#requestorAge").val((today.getYear() - birthday.getYear()) + '岁');
  validateId();
})

if ($("#dbBirthday").val()) {
  var today = new Date();
  var birthday = new Date($("#dbBirthday").val());
  $("#dbAge").val((today.getYear() - birthday.getYear()) + '岁');
  $("#dbAge").html((today.getYear() - birthday.getYear()) + '岁');
}

$("#dbBirthday").change(function() {
  var today = new Date();
  var birthday = new Date($("#dbBirthday").val());
  $("#dbAge").val((today.getYear() - birthday.getYear()) + '岁');
  validateId();
})

if ($("#coBirthday").val()) {
  var today = new Date();
  var birthday = new Date($("#coBirthday").val());
  $("#coAge").val((today.getYear() - birthday.getYear()) + '岁');
  $("#coAge").html((today.getYear() - birthday.getYear()) + '岁');
}

$("#coBirthday").change(function() {
  var today = new Date();
  var birthday = new Date($("#coBirthday").val());
  $("#coAge").val((today.getYear() - birthday.getYear()) + '岁');
  validateId();
})

// END calculate ages for requestor/coPerson/dbPerson

//validate address length:
function validateAddress() {
  var address = $("#address").val() || "";
  if (address.length < 8 && address.length > 0) {
    $("#addressError").html('地址录入过于简单，请确认是否已录入完整。')
  } else {
    $("#addressError").html('');
  }
  address = $("#coAddress").val() || "";
  if (address.length < 8 && address.length > 0) {
    $("#coAddressError").html('地址录入过于简单，请确认是否已录入完整。')
  } else {
    $("#coAddressError").html('');
  }
  address = $("#dbAddress").val() || "";;
  if (address.length < 8 && address.length > 0) {
    $("#dbAddressError").html('地址录入过于简单，请确认是否已录入完整。')
  } else {
    $("#dbAddressError").html('');
  }
}
$("#address").change(function() {
  validateAddress();
})
$("#coAddress").change(function() {
  validateAddress();
})
$("#dbAddress").change(function() {
  validateAddress();
})
validateAddress()

//bank validation check credit level

function checkCredit(creditLevel, overdueEle, boxBtnEle){
  var expanded= boxBtnEle.children().attr('class')=='fa fa-minus';
  if(creditLevel!='None'){
    if(!expanded){
      boxBtnEle.click();
    }
    if (creditLevel == 'B' || creditLevel == 'C' || creditLevel == 'D' || creditLevel == 'None') {
      overdueEle.attr('disabled', false);
    } else {
      overdueEle.val('');
      overdueEle.attr('disabled', true);
    }
  } else{
    if(expanded){
      boxBtnEle.click();
    }
  }
}
$("#mainCreditLevel").change(function() {
  checkCredit($("#mainCreditLevel").val(), $("#overdueInfo"), $("#mainCreditInfoBoxBtn"));
});
$("#comainCreditLevel").change(function() {
  checkCredit($("#comainCreditLevel").val(), $("#cooverdueInfo"), $("#coCreditInfoBoxBtn"));
});
$("#dbmainCreditLevel").change(function() {
  checkCredit($("#dbmainCreditLevel").val(), $("#dboverdueInfo"), $("#dbCreditInfoBoxBtn"));
});

if($("#mainCreditLevelValue").val()!=null){
  $("#mainCreditLevel").val($("#mainCreditLevelValue").val());
  var credtiLevel = $("#mainCreditLevel").val();
  if (credtiLevel == 'B' || credtiLevel == 'C' || credtiLevel == 'D') {
    $("#overdueInfo").attr('disabled', false);
  } else {
    $("#overdueInfo").val('');
    $("#overdueInfo").attr('disabled', true);
  }
}
if($("#comainCreditLevelValue").val()!=null) {
  $("#comainCreditLevel").val($("#comainCreditLevelValue").val());
  var credtiLevel = $("#comainCreditLevel").val();
  if (credtiLevel == 'B' || credtiLevel == 'C' || credtiLevel == 'D') {
    $("#cooverdueInfo").attr('disabled', false);
  } else {
    $("#cooverdueInfo").val('');
    $("#cooverdueInfo").attr('disabled', true);
  }
}
if($("#dbmainCreditLevelValue").val()!=null) {
  $("#dbmainCreditLevel").val($("#dbmainCreditLevelValue").val());
  var credtiLevel = $("#dbmainCreditLevel").val();
  if (credtiLevel == 'B' || credtiLevel == 'C' || credtiLevel == 'D') {
    $("#dboverdueInfo").attr('disabled', false);
  } else {
    $("#dboverdueInfo").val('');
    $("#dboverdueInfo").attr('disabled', true);
  }
}
//calculate the credit value by asset or income
$("#propertyArea").change(function () {
  if($("#creditType").val()=='1'){
    calculateAsset();
  }
});
$("#pricePerSquare").change(function () {
  if($("#creditType").val()=='1'){
    calculateAsset();
  }
})
function calculateAsset(){
  var housePrice = $("#propertyArea").val()*$("#pricePerSquare").val();
  var debt = parseFloat($("#unfinishedLoanAmount").val());
  if($("#unfinishedLoanAmountCO").length>0){
    debt+=parseFloat($("#unfinishedLoanAmountCO").val());
  }
  if($("#unfinishedLoanAmountDB").length>0){
    debt+=parseFloat($("#unfinishedLoanAmountDB").val());
  }
  var usedAmount = parseFloat($("#usedAmount").val());
  if($("#usedAmountCO").length>0){
    usedAmount+=parseFloat($("#usedAmountCO").val());
  }
  if($("#usedAmountDB").length>0){
    usedAmount+=parseFloat($("#usedAmountDB").val());
  }
  var guaranteeBalanceForOthers = parseFloat($("#guaranteeBalanceForOthers").val());
  if($("#guaranteeBalanceForOthersCO").length>0){
    guaranteeBalanceForOthers+=parseFloat($("#guaranteeBalanceForOthersCO").val());
  }
  if($("#guaranteeBalanceForOthersDB").length>0){
    guaranteeBalanceForOthers+=parseFloat($("#guaranteeBalanceForOthersDB").val());
  }
  var creditAsset = (housePrice - debt - usedAmount)*0.4 - guaranteeBalanceForOthers*0.2; //TO-DO: this 0.2 might change.
  $("#creditValue").val(creditAsset);
}

function calculateIncome(){
 var annulIncome=$("#annualIncome").val();
  var yearlyDebtSpending = parseFloat($("#yearlyDebtSpending").val());
  if($("#yearlyDebtSpendingCO").length>0){
    yearlyDebtSpending+=parseFloat($("#yearlyDebtSpendingCO").val());
  }
  if($("#annualIncomeDB").length>0){
    yearlyDebtSpending+=parseFloat($("#yearlyDebtSpendingDB").val());
  }
  var yearlyAffordableSpending = parseFloat($("#annualMustCost").val());
  var years = $("#loanYears").val();

  var creditIncome = (annulIncome - yearlyDebtSpending - yearlyAffordableSpending)*0.7*years;
  $("#creditValue").val(creditIncome);
}

function calculateCountryPrice(){
  var basicPrice = $("#basicPrice").val();
  var rate = $("#xishu").val();
  $("#pricePerSquare").val(parseFloat(basicPrice)*parseFloat(rate));
}
$("#xishu").change(function(){
  calculateCountryPrice();
});
$("#basicPrice").change(function(){
  calculateCountryPrice();
});

if($("#creditType").val()=='1'){
  calculateAsset();
}

if($("#creditType").val()=='2'){
  calculateIncome();
}
$("#creditType").change(function () {
  if($("#creditType").val()=='1'){
    calculateAsset();
  }
  if($("#creditType").val()=='2'){
    calculateIncome();
  }
});

$("#annualIncome").change(function () {
  if($("#creditType").val()=='2'){
    calculateIncome();
  }
});
$("#annualMustCost").change(function () {
  if($("#creditType").val()=='2'){
    calculateIncome();
  }
});
$("#addressCert").change(function(){
  if($("#addressCert").val()=='村委会证明'){
    $("#showRate").attr('style','display:block');
  } else {
    $("#showRate").attr('style','display:none');
  }
});
if($("#addressCert").val()=='村委会证明'){
  $("#showRate").attr('style','display:block');
} else {
  $("#showRate").attr('style','display:none');
}

function doCalucationScore(){
    $("#scoreOverlay").attr('style','');
  $("#score").html('');
  var request = {};
  request.maritalStatus = $("#maritalStatus").val();
  request.age = parseInt($("#requestorAge").val());
  request.companyNature = $("#companyNature").val();
  request.position = $("#workPosition").val();
  request.gender = $("#gender").val();
  request.education = $("#educationLevel").val();
  request.propertyType = $("#propertyType").val();
  var monthPaymentAmount = $("#monthPaymentAmount").val();
  var totalAnnualIncome = $("#annualIncome").val();
  request.monthLoanPercentage = monthPaymentAmount*12/totalAnnualIncome;
  request.downPercentage = $("#downPaymentRate").val()/100;
  request.creditLevel = $("#creditLevel").val();
  request.liveYears = $("#liveYears").val();
  request.companyYears = $("#companyYears").val();

  var score = calculateScore(request);
  if(score>70){
    $("#score").attr('class','badge bg-green');
  }else if(score>50 && score<=70){
    $("#score").attr('class','badge bg-lime');
  } else if(score>30 && score<=50){
    $("#score").attr('class','badge bg-fuchsia')
  } else {
    $("#score").attr('class','badge bg-red');
  }
 // $("#score").html(score);
  setTimeout(function () {
    $("#scoreOverlay").attr('style','display:none');
    $("#score").html(score);
  },800)

}

//calculate score trigger
$("#calculateScore").click(function () {
  doCalucationScore()
});
doCalucationScore();


